import 'package:base_library/base_library.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flukit/flukit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_study_test/app/beans/beans.dart';
import 'package:flutter_study_test/app/beans/models.dart';
import 'package:flutter_study_test/app/blocs/bloc_provider.dart';
import 'package:flutter_study_test/app/blocs/main_bloc.dart';
import 'package:flutter_study_test/app/res/strings.dart';
import 'package:flutter_study_test/app/utils/navigator_util.dart';
import 'package:flutter_study_test/app/utils/utils.dart';
import 'package:flutter_study_test/app/view/article_item.dart';
import 'package:flutter_study_test/app/view/header_item.dart';
import 'package:flutter_study_test/app/view/refresh_scaffold.dart';
import 'package:flutter_study_test/app/view/repos_item.dart';
import 'package:flutter_study_test/app/view/widget_progress.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:rxdart/rxdart.dart';

bool isHomeInit = true;

class HomePage extends StatelessWidget {
  const HomePage({Key key, this.labelId}) : super(key: key);

  final String labelId;

  Widget buildBanner(BuildContext context, List<BannerModel> list) {
    if (ObjectUtil.isEmpty(list)) {
      return new Container(height: 0.0);
    }
    return new AspectRatio(
      aspectRatio: 16.0 / 9.0,
      child: Swiper(
        indicatorAlignment: AlignmentDirectional.topEnd,
        circular: true,
        //轮播时间间隔
        interval: const Duration(seconds: 5),
        //指示器样式
        indicator: NumberSwiperIndicator(),
        children: list.map((model) {
          return new InkWell(
            onTap: () {
              LogUtil.e("BannerModel: " + model.toString());
              NavigatorUtil.pushWeb(context,
                  title: model.title, url: model.url);
            },
            child: new CachedNetworkImage(
              fit: BoxFit.fill,
              imageUrl: model.imagePath,
              placeholder: (context, url) => new ProgressView(),
              errorWidget: (context, url, error) => new Icon(Icons.error),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget buildRepos(BuildContext context, List<ReposModel> list) {
    if (ObjectUtil.isEmpty(list)) {
      return new Container(height: 0.0);
    }
    List<Widget> _children = list.map((model) {
      return new ReposItem(
        model,
        isHome: true,
      );
    }).toList();
    List<Widget> children = new List();
    children.add(new HeaderItem(
      leftIcon: Icons.book,
      title: "推荐项目",
      onTap: () {
        LogUtil.e("推荐项目: 更多" );
//        NavigatorUtil.pushTabPage(context,
//            labelId: Ids.titleReposTree, titleId: Ids.titleReposTree);
      },
    ));
    children.addAll(_children);
    return new Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: children,
    );
  }

  Widget buildWxArticle(BuildContext context, List<ReposModel> list) {
    if (ObjectUtil.isEmpty(list)) {
      return new Container(height: 0.0);
    }
    List<Widget> _children = list.map((model) {
      return new ArticleItem(
        model,
        isHome: true,
      );
    }).toList();
    List<Widget> children = new List();
    children.add(new HeaderItem(
      titleColor: Colors.green,
      leftIcon: Icons.library_books,
      title: "推荐公众号文章",
      onTap: () {
        LogUtil.e( "推荐公众号文章");
//        NavigatorUtil.pushTabPage(context,
//            labelId: Ids.titleWxArticleTree, titleId: Ids.titleWxArticleTree);
      },
    ));
    children.addAll(_children);
    return new Column(
      mainAxisSize: MainAxisSize.min,
      children: children,
    );
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.e("HomePage build......");
    RefreshController _controller = new RefreshController();

    final MainBloc bloc =MainBloc();
    //final MainBloc bloc = BlocProvider.of<MainBloc>(context);
    bloc.homeEventStream.listen((event) {
      if (labelId == event.labelId) {
        _controller.sendBack(false, event.status);
      }
    });

    if (isHomeInit) {
      LogUtil.e("HomePage init......");
      isHomeInit = false;
      Observable.just(1).delay(new Duration(milliseconds: 500)).listen((_) {
        bloc.onRefresh(labelId: labelId);
        bloc.getHotRecItem();
        bloc.getVersion();
      });
    }

    /**
     * Stream其实类似于Rx大家族，也是一种对于数据流的订阅管理。Stream可以接受任何类型的数据，值、事件、对象、集合、映射、错误、甚至是另一个Stream
     * Stream的特性就是当数据源发生变化的时候，会通知订阅者，
     * StreamBuilder是Stream在UI方面的一种使用场景，通过它我们可以在非StatefulWidget中保存状态，同时在状态改变时及时地刷新UI。
     * StreamBuilder其实是一个StatefulWidget，它通过监听Stream，发现有数据输出时，自动重建，调用builder方法。
     *
     * BLoC模式由来自Google的Paolo Soares和Cong Hui设计，并在2018年DartConf期间（2018年1月23日至24日）首次演示
     *  BLoC是Business Logic Component（业务逻辑组建）的缩写，就是将UI与业务逻辑分离，有点MVC的味道。
     */
    return new StreamBuilder(
        //需要监听的stream.
        stream: bloc.bannerStream,
        // initialData: ...初始数据，否则为空...
        builder:
            (BuildContext context, AsyncSnapshot<List<BannerModel>> snapshot) {
          return new RefreshScaffold(
            labelId: labelId,
            isLoading: snapshot.data == null,
            controller: _controller,
            enablePullUp: false,
            onRefresh: () {
              return bloc.onRefresh(labelId: labelId);
            },
            child: new ListView(
              children: <Widget>[
                new StreamBuilder(
                    stream: bloc.recItemStream,
                    builder: (BuildContext context,
                        AsyncSnapshot<ComModel> snapshot) {
                      ComModel model = bloc.hotRecModel;
                      if (model == null) {
                        return new Container(
                          height: 0.0,
                        );
                      }
                      int status = Utils.getUpdateStatus(model.version);
                      return new HeaderItem(
                        titleColor: Colors.redAccent,
                        title: status == 0 ? model.content : model.title,
                        extra: status == 0 ? 'Go' : "",
                        onTap: () {
                          if (status == 0) {
//                            NavigatorUtil.pushPage(
//                                context, RecHotPage(title: model.content),
//                                pageName: model.content);
                          } else {
                            NavigatorUtil.launchInBrowser(model.url,
                                title: model.title);
                          }
                        },
                      );
                    }),
                buildBanner(context, snapshot.data),
                new StreamBuilder(
                    stream: bloc.recReposStream,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<ReposModel>> snapshot) {
                      return buildRepos(context, snapshot.data);
                    }),
                new StreamBuilder(
                    stream: bloc.recWxArticleStream,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<ReposModel>> snapshot) {
                      return buildWxArticle(context, snapshot.data);
                    }),
              ],
            ),
          );
        });
  }
}

class NumberSwiperIndicator extends SwiperIndicator {
  @override
  Widget build(BuildContext context, int index, int itemCount) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.black45, borderRadius: BorderRadius.circular(20.0)),
      margin: EdgeInsets.only(top: 10.0, right: 5.0),
      padding: EdgeInsets.symmetric(horizontal: 6.0, vertical: 2.0),
      child: Text("${++index}/$itemCount",
          style: TextStyle(color: Colors.white70, fontSize: 11.0)),
    );
  }
}
